package labuladong.第四章;

public class LongestHuiWen {
    public static void main(String[] args) {
        System.out.println(longestPalindrome("abbaccba"));
    }

    public static String longestPalindrome(String s) {
        // 初始化为null会报空指针异常
        String res = "";
        for(int i=0; i<s.length(); i++) {
            // s[i] 为中心的最长回文串
            String s1 = palindrome(s, i, i);
            // s[i+1] 为中心的最长回文串
            String s2 = palindrome(s, i, i+1);
            res = res.length() > s1.length() ? res : s1;
            res = res.length() > s2.length() ? res : s2;
        }
        return res;
    }

    public static String palindrome(String s, int l, int r) {
        while (l>=0 && r<s.length() && s.charAt(l)==s.charAt(r)) {
            l--; r++;
        }
        // 防止ab...越界
        if(r-l-1 >= l+1){
            return s.substring(l+1, r-l-1);
        }
        return "";
    }
}
